package com.dobbinsoft.iotechn.device.mqtt;

import com.dobbinsoft.iotechn.device.enums.IotMessageType;
import com.dobbinsoft.iotechn.device.mqtt.message.IotDeviceConnectMessage;
import com.dobbinsoft.iotechn.device.mqtt.serializer.IotMqttJsonSerializer;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;


public class MqttPublishSample {

    public static void main(String[] args) {

        String topic        = "551dacd0b6b6471aaaa972d31c7aedb5";
        String content      = "Message from MqttPublishSample";
        int qos             = 2;
        String broker       = "tcp://192.168.8.229:1883";
        String clientId     = "551dacd0b6b6471aaaa972d31c7aedb5";
        // 消息持久化接口：MqttClientPersistence
//        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setUserName("551dacd0b6b6471aaaa972d31c7aedb5");
            // 现在权限鉴定还没有做，可乱传密码
            connOpts.setPassword("xxxx".toCharArray());
            System.out.println("Connecting to broker: "+broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: "+content);
            IotMqttJsonSerializer iotMqttJsonSerializer = new IotMqttJsonSerializer();
            IotDeviceConnectMessage iotDeviceConnectMessage = new IotDeviceConnectMessage();
            iotDeviceConnectMessage.setCode(IotMessageType.CONNECT.getCode());
            MqttMessage message = new MqttMessage(iotMqttJsonSerializer.toBytes(iotDeviceConnectMessage));
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } catch(MqttException me) {
            System.out.println("reason "+me.getReasonCode());
            System.out.println("msg "+me.getMessage());
            System.out.println("loc "+me.getLocalizedMessage());
            System.out.println("cause "+me.getCause());
            System.out.println("excep "+me);
            me.printStackTrace();
        }
    }
}